
//工具集合Tools
window.T = {};

// 获取请求参数
// 使用示例
// location.href = http://localhost/index.html?id=123
// T.p('id') --> 123;
var url = function(name) {
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r!=null)return  unescape(r[2]); return null;
};
T.p = url;

//请求前缀
var baseURL = "/";

//登录token
var token = localStorage.getItem("token");
if(token == 'null'){
    parent.location.href = baseURL + 'login.html';
}

//jquery全局配置
$.ajaxSetup({
	dataType: "json",
	cache: false,
    headers: {
        "token": token
    },
    complete: function(xhr) {
        //token过期，则跳转到登录页面
        if (typeof(xhr.responseJSON)!='undefined' && xhr.responseJSON.code == 401) {
            showErrorMsg("登陆信息已过期！请重新登陆", function () {
                parent.location.href = baseURL + 'login.html';
            })
        }
    }
});

//jqgrid全局配置
$.extend($.jgrid.defaults, {
    ajaxGridOptions : {
        headers: {
            "token": token
        }
    }
});

//权限判断
function hasPermission(permission) {
    if (window.parent.permissions.indexOf(permission) > -1) {
        return true;
    } else {
        return false;
    }

}

//重写alert
window.alert = function(msg, callback){
	parent.layer.alert(msg, function(index){
		parent.layer.close(index);
		if(typeof(callback) === "function"){
			callback("ok");
		}
	});
}

//重写confirm式样框
window.confirm = function(msg, callback){
	parent.layer.confirm(msg, {btn: ['确定','取消']},
	function(){//确定事件
		if(typeof(callback) === "function"){
			callback("ok");
		}
	});
}

//选择一条记录
function getSelectedRow() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
    	alert("请选择一条记录");
    	return ;
    }
    
    var selectedIDs = grid.getGridParam("selarrrow");
    if(selectedIDs.length > 1){
    	alert("只能选择一条记录");
    	return ;
    }
    
    return selectedIDs[0];
}

//选择多条记录
function getSelectedRows() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
    	alert("请选择一条记录");
    	return ;
    }
    
    return grid.getGridParam("selarrrow");
}

function getSelections(tableId,column) {
    var rows = $('#'+tableId).bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length == 0) {
        return new Array();
    }
    var ids = new Array();
    //遍历所有选择的行数据，取每条数据对应的ID
    $.each(rows, function(i, row) {
        ids[i] = row[column];
    });
    return ids;
}

$(function () {
    createErrorModal();
    createSuccessModal();
    createWarningModal();

    if (typeof(window.parent.permissions)!='undefined')
    {
        timeCall = setInterval("addTime()", 1000);
    }
});

var timeCall;

function addTime(){
    time = time + 1;
    if (time == 3600)
    {
        clearInterval(timeCall);
        parent.window.showErrorMsg("登录已超时,请重新登录!", goLoginPage);
    }
}

function goLoginPage()
{
    parent.window.location.href = "/login.html";
}

var time = 0;
var callBack = null;
var returnBack = null;
var hideObj = null;
var mode = null;

function createErrorModal()
{
    var str = "";
    str = str + "<div class='modal modal-danger'  id='errorDiv'>";
    str = str + "<div class='modal-dialog' style='padding-top: 5%;'>";
    str = str + "<div class='modal-content'>";
    str = str + "<div class='modal-header'>";
    str = str + "<button type='button' class='close' data-dismiss='modal' onclick='returnCallBack()' aria-label='Close'><span aria-hidden='true'>&times;</span></button>";
    str = str + "<h4 class='modal-title'><i class='icon fa fa-ban'></i><label style='margin-left: 10px;'>操作失败</label></h4>";
    str = str + "</div>";
    str = str + "<div class='modal-body'>";
    str = str + "<p id='errInfo'></p>";
    str = str + "</div>";
    str = str + "<div class='modal-footer'>";
    str = str + "<button type='button' class='btn btn-outline' data-dismiss='modal' onclick='returnCallBack()'>确认</button>";
    str = str + "</div>";
    str = str + "</div>";
    str = str + "</div>";
    str = str + "</div>";
    $(document.body).append(str);
}

function createSuccessModal()
{
    var str = "";
    str = str + "<div class='modal modal-success'  id='successDiv'>";
    str = str + "<div class='modal-dialog' style='padding-top: 5%;'>";
    str = str + "<div class='modal-content'>";
    str = str + "<div class='modal-header'>";
    str = str + "<button type='button' class='close' onclick='returnCallBack()' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>&times;</span></button>";
    str = str + "<h4 class='modal-title'><i class='icon fa fa-check'></i><label style='margin-left: 10px;'>操作成功</label></h4>";
    str = str + "</div>";
    str = str + "<div class='modal-body'>";
    str = str + "<p id='msgInfo'></p>";
    str = str + "</div>";
    str = str + "<div class='modal-footer'>";
    //str = str + "<button type='button' class='btn btn-outline pull-left' data-dismiss='modal'>取消</button>";
    str = str + "<button type='button' class='btn btn-outline' data-dismiss='modal' onclick='returnCallBack()'>确认</button>";
    str = str + "</div>";
    str = str + "</div>";
    str = str + "</div>";
    str = str + "</div>";
    $(document.body).append(str);
}

function createWarningModal()
{
    var str = "";
    str = str + "<div class='modal modal-warning'  tabindex='-99' role='dialog' id='warningDiv'>";
    str = str + "<div class='modal-dialog' style='padding-top: 5%;'>";
    str = str + "<div class='modal-content'>";
    str = str + "<div class='modal-header'>";
    str = str + "<button type='button' class='close' onclick='cancelBack()' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>&times;</span></button>";
    str = str + "<h4 class='modal-title'><i class='icon fa fa-warning'></i><label style='margin-left: 10px;'>提示消息</label></h4>";
    str = str + "</div>";
    str = str + "<div class='modal-body'>";
    str = str + "<p id='warningInfo'></p>";
    str = str + "</div>";
    str = str + "<div class='modal-footer'>";
    str = str + "<button type='button' class='btn btn-outline pull-left' data-dismiss='modal' onclick='cancelBack()'>取消</button>";
    str = str + "<button type='button' class='btn btn-outline' data-dismiss='modal' onclick='returnCallBack()'>确认</button>";
    str = str + "</div>";
    str = str + "</div>";
    str = str + "</div>";
    str = str + "</div>";
    $(document.body).append(str);
}

function showSuccessMsg(msg, returnFun)
{
    mode = "success";
    $("#msgInfo").html(msg);
    callBack = returnFun;
    $("#successDiv").modal();
}

function showWarningMsg(msg, returnFun, backFun)
{
    $("#warningInfo").html(msg);
    callBack = returnFun;
    returnBack = backFun;
    $("#warningDiv").modal();
}

function showErrorMsg(msg, returnFun)
{
    callBack = returnFun;
    returnBack = null;
    $("#errInfo").html(msg);
    $("#errorDiv").modal();
}

function cancelBack()
{
    if (hideObj != null)
    {
        hideObj.$element.hide(),
            hideObj.backdrop(function() {
                hideObj.$body.removeClass("modal-open"),
                    hideObj.resetAdjustments(),
                    hideObj.resetScrollbar(),
                    hideObj.$element.trigger("hidden.bs.modal")
            });
        $(".modal-backdrop").remove();
    }

    if (returnBack != null)
    {
        returnBack();
    }
}

function returnCallBack()
{
    if (mode == "success")
    {
        $("#successDiv").modal("hide");
        mode = null;
    }

    if (hideObj != null)
    {
        hideObj.$element.hide(),
            hideObj.backdrop(function() {
                hideObj.$body.removeClass("modal-open"),
                    hideObj.resetAdjustments(),
                    hideObj.resetScrollbar(),
                    hideObj.$element.trigger("hidden.bs.modal")
            });
        $(".modal-backdrop").remove();
        hideObj = null;
    }

    if (callBack != null)
    {
        callBack();
    }
}

/**
 * 将数值四舍五入(保留2位小数)后格式化成金额形式
 *
 * @param num 数值(Number或者String)
 * @return 金额格式的字符串,如'1,234,567.45'
 * @type String
 */
function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
            num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + num + '.' + cents);
}

var baseAjax = {
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json;charset=UTF-8',
    async: false,
    error: function (data, status) {
        showErrorMsg("系统异常!")
    }
};


function ajaxSubmit(url, data, returnFun, async) {
    time = 0;
    baseAjax.url = url;
    if (data != null) {
        baseAjax.data = data;
    }
    if (async === undefined) {
        baseAjax.async = false;
    } else {
        baseAjax.async = true;
    }
    baseAjax.success = function (result) {
        returnFun(result);
    };
    $.ajax(baseAjax);
}

function resetForm() {
    $("#Form").data('bootstrapValidator').destroy();

    $('#Form').data('bootstrapValidator', null);

    init();
}

function reloadPage() {
    window.location.reload();
}

